<template>
  <div class="login">
    <van-nav-bar title="登录" />
    <van-form @submit="login">
      <van-field
        v-model="mobile"
        label="手机号"
        placeholder="请输入你的手机号"
        required
        :rules="rules.mobile"
      />
      <van-field
        v-model="code"
        label="验证码"
        placeholder="请输入验证码"
        required
        :rules="rules.code"
      />
      <div style="margin: 16px">
        <van-button
          round
          block
          type="info"
          native-type="submit"
          :disabled="isLoad"
          :loading="isLoad"
          loading-text="登录中..."
        >
          登录
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { userLogin } from '@/api/user'
import { mapMutations } from 'vuex'

export default {
  name: 'Login',
  data() {
    return {
      mobile: '18949929894',
      code: '246810',
      rules: {
        mobile: [
          { required: true, message: '手机号不能为空' },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '手机号码格式错误'
          }
        ],
        code: [
          { required: true, message: '验证码不能为空' },
          {
            pattern: /^\d{6}$/,
            message: '验证码格式错误'
          }
        ]
      },
      // 是否在发送请求
      isLoad: false
    }
  },
  methods: {
    ...mapMutations('user', ['setToken']),
    async login() {
      // console.log('登录中....')
      this.isLoad = true
      try {
        const res = await userLogin(this.mobile, this.code)
        console.log(res.data)
        // this.$store.commit('setToken', res.data)
        this.setToken(res.data)
        this.$toast.success('登录成功')
        // this.$router.push('/')
        // !活的写法 获取当前路由上的back
        const back = this.$route.query.back || '/user'
        // 获取flag，有flag,使用back回退
        const flag = this.$route.query.flag
        if (flag) {
          return this.$router.back()
        }
        this.$router.push(back)
      } catch {
        this.$toast.fail('登录失败')
      }
      // 不论请求是否成功，都会执行这
      this.isLoad = false
    }
  }
}
</script>

<style></style>
